from flask import render_template, flash, redirect, url_for, request
from flask_login import current_user, login_required
from sqlalchemy import or_

from apps.forms.drift import DriftForm
from apps.models.drift import Drift
from apps.models.gift import Gift
from apps.models.user import User
from apps.models.wish import Wish
from apps.utils.enum import PendingStatus
from apps.utils.mail import send_mail
from apps.view_models.book import BookViewModel
from apps.view_models.drift import DriftViewCollection
from . import web
from apps.models.base import db

__author__ = '七月'


@web.route('/drift/<int:gid>', methods=['GET', 'POST'])
@login_required
def send_drift(gid):
    form = DriftForm(request.form)
    gift = Gift.query.get_or_404(gid)
    if Drift.query.filter_by(gift_id=gid, requester_id=current_user.id).first():
        flash('你已经发送过鱼漂了哦~(>_<)~~')
        return redirect(url_for('web.pending'))
    if request.method == 'POST' and form.validate():
        drift = Drift()
        commit_drift(form, drift, gift, gid)
        flash('鱼漂发送成功！')
        send_mail(gift.user.email, template='email/get_gift.html', subject='【鱼书】鱼漂', gift=gift, wisher=current_user)
        return redirect(url_for('web.pending'))
    if current_user.is_self(gift):
        flash('不能向自己请求书籍哦~(>_<)~~')
        return redirect(url_for('web.book_detail', isbn=gift.isbn))
    if current_user.beans < 1:
        return render_template('not_enough_beans.html', beans=current_user.beans)
    if not current_user.is_qualified():
        flash('每索取一本书，自己必须已经送出两本书哦~(>_<)~~')
        return redirect(url_for('web.book_detail', isbn=gift.isbn))
    return render_template('drift.html', gifter=gift.user.summary, user_beans=current_user.beans, form=form)


@web.route('/pending')
@login_required
def pending():
    drifts = Drift.query.filter(or_(
        Drift.requester_id == current_user.id,
        Drift.gifter_id == current_user.id)).order_by(Drift.create_time.desc()).all()
    collection = DriftViewCollection(drifts, current_user.id).drifts
    return render_template('pending.html', drifts=collection)


@web.route('/drift/<int:did>/reject')
@login_required
def reject_drift(did):
    drift = Drift.query.filter_by(gifter_id=current_user.id, id=did).first_or_404()
    with db.auto_commit():
        drift.pending = PendingStatus.reject
        wisher = User.query.get(drift.requester_id)
        wisher.beans += 1
    return redirect(url_for(('web.pending')))


@web.route('/drift/<int:did>/redraw')
@login_required
def redraw_drift(did):
    drift = Drift.query.filter_by(requester_id=current_user.id, id=did).first_or_404()
    with db.auto_commit():
        drift.pending = PendingStatus.redraw
        current_user.beans += 1
    return redirect(url_for(('web.pending')))


@web.route('/drift/<int:did>/mailed')
@login_required
def mailed_drift(did):
    drift = Drift.query.get_or_404(did)
    with db.auto_commit():
        drift.pending = PendingStatus.success
        current_user.beans += 1
        gift = Gift.query.get_or_404(drift.gift_id)
        gift.launched = True
        wish = Wish.query.filter_by(isbn=drift.isbn, uid=drift.requester_id, launched=False).first_or_404()
        wish.launched = True
    return redirect(url_for(('web.pending')))


def commit_drift(form, drift, gift, gid):
    # drift.populate_object(form)
    book = BookViewModel(gift.book)
    user = gift.user
    with db.auto_commit():
        drift.recipient_name = form.recipient_name.data
        drift.mobile = form.mobile.data
        drift.message = form.message.data
        drift.address = form.address.data
        drift.isbn = book.isbn
        drift.book_title = book.title
        drift.book_author = book.author
        drift.book_img = book.image
        drift.requester_id = current_user.id
        drift.requester_nickname = current_user.nickname
        drift.gifter_id = user.id
        drift.gift_id = gid
        drift.gifter_nickname = user.nickname
        db.session.add(drift)
        current_user.beans -= 1
